package com.share.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * created by caifan 2018/09/24
 */
public class SumTask extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 100;
    private int start;
    private int end;

    public SumTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public Integer sum() {
        Integer sum = 0;
        for (int i=start+1;i<=end;i++) {
            sum += i;
        }
        System.out.println(Thread.currentThread().getName() + ",start:" + start + ",end:" + end);
        return sum;
    }
    /**
     * The main computation performed by this task.
     *
     * @return the result of the computation
     */
    @Override
    protected Integer compute() {
        if (end - start <= 100) {
            return sum();
        }
        int middle = (start + end) / 2;
        SumTask left = new SumTask(start, middle);
        SumTask right = new SumTask(middle, end);
        left.fork();
        right.fork();
        return left.join() + right.join();
    }

}
